package org.lanyu.springainovel.novel.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.lanyu.springainovel.common.util.SecurityContextUtil;
import org.lanyu.springainovel.common.vo.RestVO;
import org.lanyu.springainovel.novel.entity.Inspiration;
import org.lanyu.springainovel.novel.service.InspirationService;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 灵感管理控制器
 */
@Slf4j
@Tag(name = "灵感管理", description = "灵感管理相关接口")
@RestController
@RequestMapping("/novel/inspiration")
@RequiredArgsConstructor
public class InspirationController {

    private final InspirationService inspirationService;
    
    @Operation(summary = "获取灵感列表", description = "分页获取用户的所有灵感")
    @GetMapping("/list")
    public RestVO<IPage<Inspiration>> getInspirationList(
            @RequestParam(defaultValue = "1") Integer current,
            @RequestParam(defaultValue = "10") Integer size,
            @RequestParam(required = false) String title,
            @RequestParam(required = false) String tags,
             @RequestParam(required = false) Long bookId,
            @RequestParam(required = false) Integer rating,
            @RequestParam(required = false) Long userId) {
        try {
            Page<Inspiration> page = new Page<>(current, size);
            QueryWrapper<Inspiration> queryWrapper = new QueryWrapper<>();
            
            if (title != null && !title.trim().isEmpty()) {
                queryWrapper.like("title", title);
            }
            
            if (tags != null && !tags.trim().isEmpty()) {
                queryWrapper.like("tags", tags);
            }
             if (bookId != null) {
                queryWrapper.eq("book_id", bookId);
            }
            
            if (rating != null) {
                queryWrapper.eq("rating", rating);
            }
            
            if (userId != null) {
                queryWrapper.eq("user_id", userId);
            }
            
            queryWrapper.orderByDesc("rating",  "update_time");
            
            IPage<Inspiration> result = inspirationService.page(page, queryWrapper);
            return RestVO.success(result);
        } catch (Exception e) {
            log.error("获取灵感列表失败", e);
            return RestVO.fail("获取灵感列表失败: " + e.getMessage());
        }
    }

    @Operation(summary = "获取灵感详情", description = "根据ID获取灵感详细信息")
    @GetMapping("/{id}")
    public RestVO<Inspiration> getInspirationById(@PathVariable Long id) {
        try {
            Inspiration inspiration = inspirationService.getInspirationById(id);
            if (inspiration == null) {
                return RestVO.fail("灵感不存在");
            }
            return RestVO.success(inspiration);
        } catch (Exception e) {
            log.error("获取灵感详情失败", e);
            return RestVO.fail("获取灵感详情失败: " + e.getMessage());
        }
    }

    @Operation(summary = "创建灵感", description = "创建新的灵感")
    @PostMapping
    public RestVO<Inspiration> createInspiration(@RequestBody Inspiration inspiration) {
        try {
            // 从JWT获取当前用户ID
            Long currentUserId = SecurityContextUtil.getCurrentUserId();
            if (currentUserId == null) {
                return RestVO.fail("用户未登录");
            }
            
            // 设置当前用户ID
            inspiration.setUserId(currentUserId);
            
            Inspiration createdInspiration = inspirationService.createInspiration(inspiration);
            return RestVO.success(createdInspiration);
        } catch (Exception e) {
            log.error("创建灵感失败", e);
            return RestVO.fail("创建灵感失败: " + e.getMessage());
        }
    }

    @Operation(summary = "更新灵感", description = "更新灵感信息")
    @PutMapping("/{id}")
    public RestVO<Inspiration> updateInspiration(@PathVariable Long id, @RequestBody Inspiration inspiration) {
        try {
            inspiration.setId(id);
            Inspiration updatedInspiration = inspirationService.updateInspiration(inspiration);
            return RestVO.success(updatedInspiration);
        } catch (Exception e) {
            log.error("更新灵感失败", e);
            return RestVO.fail("更新灵感失败: " + e.getMessage());
        }
    }

    @Operation(summary = "删除灵感", description = "根据ID删除灵感")
    @DeleteMapping("/{id}")
    public RestVO<Boolean> deleteInspiration(@PathVariable Long id) {
        try {
            boolean success = inspirationService.removeById(id);
            if (success) {
                return RestVO.success(true);
            } else {
                return RestVO.fail("删除失败，灵感可能不存在");
            }
        } catch (Exception e) {
            log.error("删除灵感失败", e);
            return RestVO.fail("删除灵感失败: " + e.getMessage());
        }
    }

    @Operation(summary = "获取用户灵感", description = "获取指定用户的所有灵感")
    @GetMapping("/user/{userId}")
    public RestVO<List<Inspiration>> getInspirationsByUserId(@PathVariable Long userId) {
        try {
            List<Inspiration> inspirations = inspirationService.getInspirationsByUserId(userId);
            return RestVO.success(inspirations);
        } catch (Exception e) {
            log.error("获取用户灵感失败", e);
            return RestVO.fail("获取用户灵感失败: " + e.getMessage());
        }
    }

    @Operation(summary = "获取书籍灵感", description = "获取指定书籍的所有灵感")
    @GetMapping("/book/{bookId}")
    public RestVO<List<Inspiration>> getInspirationsByBookId(@PathVariable Long bookId) {
        try {
            List<Inspiration> inspirations = inspirationService.getInspirationsByBookId(bookId);
            return RestVO.success(inspirations);
        } catch (Exception e) {
            log.error("获取书籍灵感失败", e);
            return RestVO.fail("获取书籍灵感失败: " + e.getMessage());
        }
    }

    @Operation(summary = "根据标签获取灵感", description = "根据标签获取公开灵感")
    @GetMapping("/tags/{tags}")
    public RestVO<List<Inspiration>> getInspirationsByTags(@PathVariable String tags) {
        try {
            List<Inspiration> inspirations = inspirationService.getInspirationsByTags(tags);
            return RestVO.success(inspirations);
        } catch (Exception e) {
            log.error("根据标签获取灵感失败", e);
            return RestVO.fail("根据标签获取灵感失败: " + e.getMessage());
        }
    }

    @Operation(summary = "根据用户ID和标签获取灵感", description = "根据用户ID和标签获取灵感")
    @GetMapping("/user/{userId}/tags/{tags}")
    public RestVO<List<Inspiration>> getInspirationsByUserIdAndTags(
            @PathVariable Long userId, 
            @PathVariable String tags) {
        try {
            List<Inspiration> inspirations = inspirationService.getInspirationsByUserIdAndTags(userId, tags);
            return RestVO.success(inspirations);
        } catch (Exception e) {
            log.error("根据用户ID和标签获取灵感失败", e);
            return RestVO.fail("根据用户ID和标签获取灵感失败: " + e.getMessage());
        }
    }

    @Operation(summary = "获取热门灵感", description = "获取热门灵感")
    @GetMapping("/hot")
    public RestVO<List<Inspiration>> getHotInspirations(@RequestParam(defaultValue = "10") Integer limit) {
        try {
            List<Inspiration> inspirations = inspirationService.getHotInspirations(limit);
            return RestVO.success(inspirations);
        } catch (Exception e) {
            log.error("获取热门灵感失败", e);
            return RestVO.fail("获取热门灵感失败: " + e.getMessage());
        }
    }
}